<template>
    <div class="forbid-select index">
        <div class="index-header">
            <div class="index-title animate__bounceInTop" style="color: white;">
                <div @click="go" class="cursor-pointer">
                    {{ webInfo.websiteName }}
                </div>
            </div>
            <div class="flex-display-center animate__animated animate__fadeInLeftBig">
                <div class="typewriter">
                    <div class="typing">曾梦想仗剑走天涯, 看一看世界的繁华</div>
                </div>
            </div>
        </div>
        <icon :class="`weather-icon-${currentWeather.icon} weather animate__animated animate__fadeInRight`"
            @mouseenter="weatherEnter" @mouseleave="weatherLeave" @dblclick="getWeather(true)" />
        <transition class="animate__animated " enter-active-class="animate__rotateInCenter"
            leave-active-class="animate__rotateOutCenter">
            <div v-show="showWeatherInfo" class="weather-info">
                <div class="flex-display-center" style="padding-bottom: 10px;">
                    <div class="info-label">
                        {{ location.ad_info.city + location.ad_info.district }}
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label">今天天气:</div>
                    <div class="info-value">
                        {{ miWeatherMap[weather.day.from]?.name + (weather.day.to === weather.day.from ? '' : '转' +
                            miWeatherMap[weather.day.to]?.name) || '晴' }}
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label">实时天气:</div>
                    <div class="info-value">
                        {{ miWeatherMap[weather.weather]?.name || weather.weather || '晴' }}
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label">室外温度:</div>
                    <div class="info-value">
                        {{ weather.temperature.value + weather.temperature.unit }}
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label">体感温度:</div>
                    <div class="info-value">
                        {{ weather.feelsLike.value + weather.feelsLike.unit }}
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label">空气湿度:</div>
                    <div class="info-value">
                        {{ weather.humidity.value + weather.humidity.unit }}
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label">大气压强:</div>
                    <div class="info-value">
                        {{ weather.pressure.value + weather.pressure.unit }}
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label">紫外线:</div>
                    <div class="info-value">
                        {{ uvIndex[weather.uvIndex] || '很弱' }}
                    </div>
                </div>
            </div>
        </transition>

        <el-footer class="default-style animate__animated animate__fadeInUp">
            <div class="flex-display-center" style="height: 50%;">
                <div class="webInfo">
                    <div class="beian">联系我们：
                        <span>{{ webInfo.email }}</span>
                    </div>
                </div>
                <div style="width: 300px;text-align: center;">{{ now.format('YYYY年M月D日 星期dd H时m分s秒') }}</div>
                <div style="padding: 0 5px;">
                    {{ calendarInfo.gzYear }}年{{ calendarInfo.IMonthCn }}{{ calendarInfo.IDayCn }}
                </div>
            </div>
            <div class="flex-display-center" style="height: 50%;">
                <div class="webInfo">
                    <div class="beian beian_gov" v-if="webInfo.icpNumber" @click="intoGovBeian">
                        {{ webInfo.icpNumber }}
                    </div>
                    <div class="beian beian_gov" style="display: flex" v-if="webInfo.gaNumber" @click="intoGABeian">
                        <img :src="beian" class="beianImg" alt="beian">
                        <div style="margin-left: 5px">{{ webInfo.gaNumber }}</div>
                    </div>
                    <div class="beian cursor-default">{{ copyRightInfo }}</div>
                </div>
            </div>
        </el-footer>
    </div>
</template>

<script setup>
import beian from "@/assets/image/beian.png"
import { useModalSize, useRequest } from "@usehook"
import { useNow, useOnline, useEventListener, useParallax } from '@vueuse/core'
import { jsonp } from "@/utils/tools"
import { apiPrefix } from "@/utils/constant"
import { broadcastEmitter } from "@/utils/eventbus"
import storeInstance, { storeToRefs } from "@/pinia"
import { calendar } from '@/utils/calendar'
import router from "@/router"

const uvIndex = {
    "0": "很弱",
    "1": "很弱",
    "2": "很弱",
    "3": "弱",
    "4": "弱",
    "5": "中等",
    "6": "中等",
    "7": "强",
    "8": "强",
    "9": "很强",
    "10": "很强",
}

let timeout = $ref(null)
let calendarInfo = $ref({})
let showWeatherInfo = $ref(false)

const { now } = useNow({ controls: true, interval: 1000 })

const onlineColor = $computed(() => {
    return useOnline().value ? "orange" : "red"
})

const getLocationInfo = () => {
    let url = "https://apis.map.qq.com/ws/location/v1/ip"
    return jsonp(url, {
        key: "DCUBZ-FBWRZ-XIIXU-TGCMF-XCJJE-VGB22",
        output: 'jsonp'
    })
}

const weatherEnter = () => {
    clearTimeout(timeout)
    showWeatherInfo = true
}
const weatherLeave = () => {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
        showWeatherInfo = false
    }, 500)
}

let weather = $ref({
    temperature: { unit: "℃", value: "0" },
    feelsLike: { unit: "℃", value: "0" },
    humidity: { unit: "%", value: "10" },
    pressure: { unit: "hPa", value: "100" },
    day: { from: 0, to: 0 }
})
let currentWeather = $ref("")
let location = $ref({ ad_info: { province: "", city: "", district: "" } })
let miWeatherMap = $ref({})

const locationKey = "location"
const getLocation = () => {
    return JSON.parse(sessionStorage.getItem(locationKey) || "{}")
}

const setLocation = (location) => {
    return sessionStorage.setItem(locationKey, JSON.stringify(location))
}

const getCalendar = () => {
    const now = new Date()
    calendarInfo = calendar.solar2lunar(now.getFullYear(), now.getMonth() + 1, now.getDate())
}

const getWeather = async (refresh) => {
    if (refresh || !weather.updateTime || new Date().getTime() - weather.updateTime > 300000) {
        let newLocation = getLocation()
        if (refresh || !newLocation || Object.keys(newLocation).length === 0) {
            const locationResp = await getLocationInfo()
            setLocation(locationResp.result)
            newLocation = locationResp.result
        }
        location = newLocation
        useRequest({
            url: apiPrefix + '/weather',
            latitude: location.location.lat, longitude: location.location.lng
        }).then(resp => {
            if (resp && resp.status) {
                const mapData = resp.data.dict

                for (let dict of Object.keys(mapData)) {
                    const splitData = mapData[dict].split("@")
                    mapData[dict] = { name: splitData[1], icon: splitData[0] }
                }
                miWeatherMap = mapData

                weather = resp.data.current
                weather.updateTime = resp.data.updateTime
                weather.day = resp.data.forecastDaily.weather.value[0]
                currentWeather = miWeatherMap[weather.weather]
            }
        })
    }
}

const go = () => {
    //手机模式禁止点击
    if (document.documentElement.classList.contains("mobile")) return
    broadcastEmitter("showLogin")
}

const { getWebInfo: webInfo = {
    email: "",
    icpNumber: "",
    gaNumber: "",
    websiteName: "",
    name: "",
    captcha: false,
    allowUserPwd: false,
    expireTime: 60,
    domain: ""
} } = storeToRefs(storeInstance.mainStore)

// 网站版权信息
const copyRightInfo = computed(() => {
    return "Copyright@ 2023 - " + new Date().getFullYear() + " " + webInfo.value.websiteName + "/" + webInfo.value.domain + " All  Rights Reserved"
})

// 打开公安备案
const intoGABeian = () => {
    window.open('https://beian.mps.gov.cn/#/query/webSearch?code=32080402000277', '_blank')
}
// 打开网站备案
const intoGovBeian = () => {
    window.open('https://beian.miit.gov.cn/#/Integrated/index', '_blank');
}

const darkDocument = document.querySelector('.dark-background')
const parallax = reactive(useParallax(document.querySelector('.dark-background')))

const index = $computed(() => {
    return router.currentRoute.value.path === '/'
})
watch(() => parallax, (value) => {
    if (index) darkDocument.style.transform = `translateX(${value.tilt * 20}px) translateY(${value.roll * 20}px) scale(1.05)`
}, { deep: true })

onActivated(() => {
    // 删除地址栏参数，不触发页面重新加载
    // if (history) history.replaceState({}, '', "/")
    clearTimeout(timeout)
    darkDocument.style.transition = '1s ease-out all'
    darkDocument.style.transform = `scale(1.05)`
    getWeather()
    getCalendar()
})

onDeactivated(() => {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
        darkDocument.style.transition = ''
    }, 1000)

    darkDocument.style.transform = 'scale(1)'
})

useEventListener('resize', () => {
    clearTimeout(timeout)
    darkDocument.style.transition = ""
    timeout = setTimeout(() => {
        darkDocument.style.transition = '.3s ease-out all'
    }, 500)
})

onBeforeMount(() => {
    useModalSize.reset()
})
</script>

<style scoped lang="scss">
@keyframes fadeOutLeft {
    from {
        opacity: 1;
    }

    to {
        opacity: 0;
        -webkit-transform: translate3d(-100%, v-bind(y + 'px'), 0);
        transform: translate3d(-100%, v-bind(y + 'px'), 0);
    }
}

.animate__fadeOutLeft {
    -webkit-animation-name: fadeOutLeft;
    animation-name: fadeOutLeft;
}

.index {
    height: 100%;
    width: 100%;
    position: absolute !important;
    top: 0;
    left: 0;
}

:deep(.el-footer) {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    height: 100%;
    max-height: 60px;
    color: #ffffff;

    @media screen and (min-width: 1000px) and (max-width: 1250px) {
        height: 60px !important;
    }
}

.mobile .el-footer {
    display: none;
}

:deep(.beianImg) {
    width: 17px;
    height: 17px;
    margin: auto;
}

:deep(.beian+.beian) {
    margin-left: 20px;
    cursor: default;
}

:deep(.beian_gov:hover) {
    text-decoration: underline
}

:deep(.webInfo) {
    display: flex;
    padding: 5px 0;
}

.index-header {
    position: absolute;
    top: 25vh;
    width: 100vw;
    font-family: fojiya, cursive, monospace;
    font-weight: bold;
}

:deep(.index-title) {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 30px;
    font-size: 60px;
}


:deep(.typewriter) {
    margin: 15px auto 0 auto;
}

/* CSS样式 */
:deep(.typewriter) {
    width: fit-content;
    text-align: center;
    padding: 0 10px;
    margin: auto;
    background: rgba(0, 0, 0, .3);
    border-radius: var(--border-radius);
}

:deep(.typewriter .typing) {
    color: #ffffff;
    overflow: hidden;
    border-right: .15em solid v-bind(onlineColor);
    white-space: nowrap;
    margin: 10px auto;
    letter-spacing: .15em;
    animation: typing 10s steps(30, end) infinite forwards, blink-caret 1.2s step-end infinite forwards;
}

@keyframes typing {
    0% {
        width: 0
    }

    35%,
    55% {
        width: 20em;
    }

    85%,
    100% {
        width: 0;
    }
}

@keyframes blink-caret {

    from,
    to {
        border-color: transparent
    }

    50% {
        border-color: v-bind(onlineColor)
    }
}

:deep(.weather) {
    position: absolute;
    top: 0;
    right: 5px;
}

:deep(.weather-info) {
    position: absolute;
    top: 50px;
    right: 5px;
    width: fit-content;
    background: rgba(0, 0, 0, .2);
    backdrop-filter: blur(5px);
    padding: 10px;
    box-shadow: -1px 1px 5px rgb(98 98 98 / 20%) inset;
    font-size: 16px;
    border-radius: var(--border-radius);
}

:deep(.calendar-info) {
    position: absolute;
    top: 5px;
    left: 5px;
    width: fit-content;
    max-width: 350px;
    background: rgba(0, 0, 0, .2);
    backdrop-filter: blur(5px);
    padding: 10px;
    box-shadow: -1px 1px 5px rgb(98 98 98 / 20%) inset;
    font-size: 16px;
    border-radius: var(--border-radius);
}

:deep(.calendar-info:hover .close-icon) {
    opacity: 1;
    transition: opacity .3s ease-in;
}

:deep(.close-icon) {
    position: absolute;
    right: 5px;
    top: 5px;
    color: antiquewhite;
    opacity: 0;
    transition: opacity .3s ease-out;
}

:deep(.info-item) {
    display: flex;
    align-items: center;
}

:deep(.info-item+.info-item) {
    padding-top: 10px;
}

:deep(.calendar-info .info-label) {
    min-width: 90px;
    text-align: right;
}

:deep(.info-label) {
    color: antiquewhite;
}

:deep(.info-value) {
    color: antiquewhite;
    padding-left: 5px;
}

.mobile {
    .calendar-info {
        max-width: 200px;
        font-size: var(--font-size);

        .info-label {
            min-width: 60px
        }
    }

    .weather-info {
        font-size: var(--font-size);
    }
}
</style>